#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-05-23 18:15
# @Author   : BYF
# file      : db.py
# @version  :


from lefull.conf.config import Config
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


class DataBase(object):
    def __init__(self):
        """
        初始化数据库链接
        """
        self.config = Config()
        self.db_host = self.config.db_host
        self.db_port = self.config.db_port
        self.db_user = self.config.db_user
        self.db_password = self.config.db_password
        self.db_name = self.config.db_name
        self.engine = create_engine(
            "mysql+pymysql://{user}:{password}@{db_host}:{port}/{name}".format(
                user=self.db_user,
                password=self.db_password,
                db_host=self.db_host,
                port=self.db_port,
                name=self.db_name
            ),
            echo=True
        )

    def create_session(self):
        """
        创建会话
        :return:
        """
        DBSession = sessionmaker(bind=self.engine)
        session = DBSession()
        print("\n创建数据库会话, session为：{session}".format(session=session))
        return session

    def close_session(self, session):
        """
        关闭会话
        :param session:
        :return:
        """
        print("\n关闭数据库会话, session为：{session}".format(session=session))
        session.close()

    def get_data(self, table_name):
        session = self.create_session()
        data = session.query(table_name)
        self.close_session(session)
        return data


db = DataBase()


def get_db_data(table_name):
    session = db.create_session()
    data = session.query(table_name)
    db.close_session(session)
    return data


if __name__ == '__main__':
    DataBase()
